package com.myapplication.helper;

import android.content.Context;
import android.content.SharedPreferences;

import com.myapplication.model.UserInfo;


/**
 * Created by Administrator on 2016/4/14.
 */
public class PreferencesHelper {

    private static final String USER_INFO = "userPreferences";
    private static final String USER_PASSWORD = "password";
    private static final String USER_NAME = "username";
    private static final String USER_KEY = "key";

    public PreferencesHelper() {

    }

    public static void writetoPreference(Context context, UserInfo userInfo) {
        SharedPreferences.Editor editor = getEdit(context);

        editor.putString(USER_PASSWORD, userInfo.getPassword());
        editor.putString(USER_NAME, userInfo.getUsername());
        editor.putString(USER_KEY, userInfo.getKey());
        editor.apply();
        //  editor.commit();

    }

    public static UserInfo getUserInfo(Context context) {
        SharedPreferences sharedPreferences = getSharedPreferences(context);

        final String teacherpassword = sharedPreferences.getString(USER_PASSWORD, null);
        final String username = sharedPreferences.getString(USER_NAME, null);
        final String key = sharedPreferences.getString(USER_KEY, null);


        if (null == username || null == teacherpassword || null == key) {
            return null;
        }
        UserInfo userInfo = new UserInfo();

        userInfo.setPassword(teacherpassword);
        userInfo.setUsername(username);
        userInfo.setKey(key);


        return userInfo;
    }

    public static void signOut(Context context) {
        SharedPreferences.Editor editor = getEdit(context);

        editor.remove(USER_NAME);
        editor.remove(USER_PASSWORD);
        editor.remove(USER_KEY);
        editor.apply();
    }

    public static boolean isSignedIn(Context context) {
        final SharedPreferences preferences = getSharedPreferences(context);
        return preferences.contains(USER_PASSWORD) &&
                preferences.contains(USER_NAME) &&
                preferences.contains(USER_KEY);

    }

    public static SharedPreferences.Editor getEdit(Context context) {
        SharedPreferences sharedPreferences = getSharedPreferences(context);
        return sharedPreferences.edit();
    }

    public static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE);
    }

}
